package com.github.tangmonkmeat;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Description:
 *
 * @author zwl
 * @version 1.0
 * @date 2021/8/6 下午2:06
 */
public class 遍历螺旋数组 {

    public static void main(String[] args) {
        int[] ints = SpiralMatrix(new int[][]{{1}});

        System.out.println(Arrays.toString(ints));
    }

    public static int[] SpiralMatrix (int[][] matrix) {
        // write code here
        final int cap = matrix.length * matrix[0].length;
        List<Integer> res = new ArrayList<>(cap);
        int count = 0;
        int t = 0;
        while(count < cap){
            int i = t;
            int j = t;
            for(;j < matrix[0].length - t && count < cap;j++){
                res.add(matrix[i][j]);
                count++;
            }
            j--;
            i++;
            for(;i < matrix.length - t && count < cap;i++){
                res.add(matrix[i][j]);
                count++;
            }
            i--;
            j--;
            for(;j >= t && count < cap;j--){
                res.add(matrix[i][j]);
                count++;
            }
            i--;
            j++;
            for(;i > t && count < cap;i--){
                res.add(matrix[i][j]);
                count++;
            }
            t++;
        }

        return res.stream()
                .mapToInt(Integer::valueOf)
                .toArray();
    }

}
